package simmar.input;

import simmar.input.InputKnowledge;
import ch.idsia.agents.Agent;
import ch.idsia.agents.controllers.human.HumanKeyboardAgent;
import ch.idsia.benchmark.mario.environments.Environment;
import ch.idsia.benchmark.mario.engine.GeneralizerLevelScene;
import ch.idsia.benchmark.mario.engine.sprites.Sprite;

public class InputAgent extends HumanKeyboardAgent implements Agent
{
	protected InputKnowledge knowledge;
	byte[][] lastGrid;
		
	public void reset()
	{
		if (knowledge != null) {
			knowledge.reset();
		} else {
			knowledge = new InputKnowledge();
		}
		lastGrid = null;
		super.reset();
	}
	
	public void integrateObservation(Environment environment)
	{
		knowledge.update(environment);

		//printGrid(environment);
		
		if (knowledge.marioSpeed[1] > 0.0f) {
			System.out.println("Counter: " + knowledge.marioJumpCounter + ", Speed: " + knowledge.marioSpeed[1]);
		}
		
		super.integrateObservation(environment);
	}
	
	public boolean[] getAction() {
		boolean[] actions = super.getAction();
		
		if (actions[3]) {
			knowledge.jumpStart();
		}
		
		return actions;
	}
	
	private void printGrid(Environment environment)
	{
		int[] marioposego = environment.getMarioEgoPos();
		
		byte[][] grid = environment.getMergedObservationZZ(1,2);
		grid[marioposego[0]][marioposego[1]] = Sprite.KIND_MARIO;
		
		// Check if it is identical to the last one
		//System.out.println("Grid: " + grid + " - lastGrid: " + lastGrid);
		boolean identical = true;
		if (lastGrid != null) {
			for (int y = 0; y < grid.length; y++) {
				for (int x = 0; x < grid[y].length; x++) {
					if (grid[y][x] != lastGrid[y][x]) {
						identical = false;
						break;
					}
				}
			}
		} else {
			identical = false;
		}
		
		// Copy grid
		lastGrid = new byte[grid.length][grid[0].length];
		for (int y = 0; y < grid.length; y++) {
			for (int x = 0; x < grid[y].length; x++) {
				lastGrid[y][x] = grid[y][x];
			}
		}
		
		// Print it if not identical
		if (!identical) {
			for (int y = 0; y < grid.length; y++) {
				System.out.print("|");
				for (int x = 0; x < grid[y].length; x++) {
					if (grid[y][x] == GeneralizerLevelScene.BRICK) {
						System.out.print("B|");
					} else if (grid[y][x] == GeneralizerLevelScene.BORDER_CANNOT_PASS_THROUGH) {
						System.out.print("X|");
					} else if (grid[y][x] == GeneralizerLevelScene.BORDER_HILL) {
						System.out.print("H|");
					} else if (grid[y][x] == GeneralizerLevelScene.FLOWER_POT_OR_CANNON) {
						System.out.print("F|");
					} else if (grid[y][x] == GeneralizerLevelScene.COIN_ANIM) {
						System.out.print("C|");
					} else if (grid[y][x] == Sprite.KIND_MARIO) {
						System.out.print("M|");
					} else if (grid[y][x] == 1) {
						System.out.print("E|");
					} else {
						System.out.print(" |");
					}
				}
				System.out.println();
			}
			System.out.println();
		}
	}
};